<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage, NDataTable
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, formatDateTime, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"
import { exportToExcel } from '@/utils/exportUtils'


defineOptions({ name: '退货' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  data_ini:{
    type: [],
    category_id:[]
  },
   config:[],
   durgs:[],
    DrugsDepository:[],
    DrugsNumber:[],
    select_durg_id:null
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '退货',
  initForm: {},
  doCreate: api.createDrugsBills,
  doUpdate: api.updateDrugsBills,
  doDelete: api.deleteDrugsBills,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
  queryItems.value.type=5
  $table.value?.handleSearch()
  api.getProjectIni().then((res) => (data.data_ini = res.data))
})

const columns = [
    {
    title: '+',
    width: 60,
    key: 'details_mx',
    align: 'center',
    type: 'expand',
    expandable: row => row.details_mx !== null,
    renderExpand: (row) => {
      let details_mx = row.details_mx ?? []
      let sku_columns=[
          {
          width:"auto",
          title: '仓库',
          key: 'depository_name'
        },
        {
          width:"auto",
          title: '药品id',
          key: 'drugs_id'
        },
        {
          width:"auto",
          title: '药品名称',
          key: 'drugs.drugs_name'
        },
        {
          width:"auto",
          title: '规格',
          key: 'drugs.spec'
        },
          {
          width:"auto",
          title: '单位',
          key: 'drugs.unit'
        },
          {
          width:"auto",
          title: '批号',
          key: 'batch',
          render(row) {
            return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 0px' } }, { default: () => row.batch })
          },
        },
          {
          width:"auto",
          title: '批准文号',
          key: 'drugs.approval_number',
          render(row) {
            return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 0px' } }, { default: () => row.drugs.approval_number })
          },
        },
        {
          width:"auto",
          title: '单号',
          key: 'type_id',
          render(row) {
            return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 0px' } }, { default: () => row.type_id })
          },
        },
          {
          width:"auto",
          title: '单价',
          key: 'unit_price'
        }, {
          width:"auto",
          title: '数量',
          key: 'total_number'
        }, {
          width:"auto",
          title: '合计金额',
          key: 'total_price'
        },{
          width:"auto",
          title: '税率(%)',
          key: 'rate'
        },{
          width:"auto",
          title: '过期时间',
          key: 'valid_at'
        },{
          width:"auto",
          title: '供应商',
          key: 'supplier'
        },
      ]
      return h(NDataTable, { columns: sku_columns,striped:true ,size:"small",data:details_mx, style: { width: '100%',margin:'10px 0px' }  })
    }
  },
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '类型',
    key: 'type_name',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.type_name })
    },
  },
    {
    title: '退货厂家',
    key: 'return_user',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.return_user })
    },
  },

  {
    title: '备注',
    key: 'remark',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '创建人',
    key: 'created_uname',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '报损时间',
    key: 'add_time',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },


  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '作废',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                []
              ),
            default: () => h('div', {}, '确定作废该数据吗?'),
          }
        ),
      ]
    },
  },
]



const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['input', 'blur'],
    },
  ],
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据
    const { data: tableData } = await api.getDrugsBillsList({
      ...queryItems.value,
      type: 5,
      is_export: 1
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.flatMap(item => {
      const baseData = {
        ID: item.id,
        类型: item.type_name,
        退货厂家: item.return_user,
        备注: item.remark,
        创建人: item.created_uname,
        退货时间: item.add_time
      }

      if (!item.details_mx || item.details_mx.length === 0) {
        return [baseData]
      }

      return item.details_mx.map(detail => ({
        ...baseData,
        仓库: detail.depository_name,
        药品ID: detail.drugs_id,
        药品名称: detail.drugs?.drugs_name,
        规格: detail.drugs?.spec,
        单位: detail.drugs?.unit,
        批号: detail.batch,
        批准文号: detail.drugs?.approval_number,
        单号: detail.type_id,
        单价: detail.unit_price,
        数量: detail.total_number,
        合计金额: detail.total_price,
        税率: detail.rate,
        过期时间: detail.valid_at,
        供应商: detail.supplier
      }))
    })

    // 导出Excel
    exportToExcel(exportData, `退货记录_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

const onCreate = () => {
  return {
      depository_id:null,
      drugs_id:null,
      bat_id:null,
      total_number:1,
      DrugsDepository:[],
      DrugsNumber:[]
  }
}
function on_add(){
  handleAdd()
  modalForm.value.type=5
  modalForm.value.add_time = formatDateTime(new Date())
  get_ini()
}

function get_ini(){
  api.getConfig().then((res) => {
    data.config = res.data
  })
  api.getDrugsAll().then((res) => (data.durgs = res.data))
}

function change_DrugsDepository(newDrugId,value){
  api.getDrugsDepository({
    q: newDrugId,
  }).then((res) => {
    value.DrugsDepository = res.data
    data.select_durg_id = newDrugId
  })
}

function change_DrugsNumber(newId,value){
  api.getDrugsNumber({
    drugs_id: data.select_durg_id,
    depository_id: newId,
  }).then((res) => {
    value.DrugsNumber = res.data
  })
}

</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton style="margin-left: 1350px;" type="info" @click="handleExport">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
          </NButton>
          <NButton  type="primary" @click="on_add">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建{{ nameFromInstance }}
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getDrugsBillsList"
           :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="操作时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>

          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
          style="width: 1100px"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
            <n-tabs type="line" animated size="large" pane-style="padding: 20px 0 0 0;">
              <n-tab-pane name="基础信息">
                 <NFormItem label="报损时间" path="add_time">
                  <n-date-picker
                    v-model:formatted-value="modalForm.add_time"
                    type="datetime"
                    clearable
                    placeholder="报损时间"
                    style="width: 100%"
                  />
                </NFormItem>
                <NFormItem label="退货厂家" path="return_user">
                  <NInput v-model:value="modalForm.return_user" clearable placeholder="退货厂家" />
                </NFormItem>
                <NFormItem label="备注" path="remark">
                  <NInput type="textarea" v-model:value="modalForm.remark" clearable placeholder="请输入备注" />
                </NFormItem>

              </n-tab-pane>
              <n-tab-pane name="单据明细">
                <NFormItem label="" path="details">
                  <n-layout>
                        <n-layout-header>
                          <n-flex >
                            <n-tag size="large" style="width: 250px"> 药品 </n-tag>
                            <n-tag size="large" style="width: 150px"> 仓库 </n-tag>
                            <n-tag size="large" style="width: 300px"> 批号 </n-tag>
                            <n-tag size="large" style="width: 100px"> 数量</n-tag>
                          </n-flex>
                        </n-layout-header>
                        <n-layout-content content-style="padding: 10px 0;" >

                          <n-dynamic-input v-model:value="modalForm.details" :on-create="onCreate">
                            <template #default="{ value , index}">
                              <n-flex justify="space-between">

                                <n-cascader style="width: 250px;" v-model:value="value.drugs_id"
                                  clearable
                                  placeholder="请选择药品"
                                  :options="data.durgs"
                                  cascade
                                  check-strategy="children"
                                  show-path
                                  filterable
                                  clear-filter-after-select
                                  label-field="name"
                                  value-field="id"
                                  @update:value="(newDrugId) => change_DrugsDepository(newDrugId, value)"
                                />

                                <NSelect
                                  v-model:value="value.depository_id"
                                  :options="value.DrugsDepository"
                                  placeholder="请选择仓库"
                                  filterable
                                  label-field="name"
                                  value-field="id"
                                  style="width: 150px"
                                  @update:value="(newId) => change_DrugsNumber(newId, value)"
                                />
                                <NSelect
                                  v-model:value="value.bat_id"
                                  :options="value.DrugsNumber"
                                  placeholder="请选择单号"
                                  filterable
                                  label-field="name"
                                  value-field="id"
                                  style="width: 300px"
                                />

                                <n-input-number :min="0" placeholder="数量" v-model:value="value.total_number" style="width: 100px"/>
                              </n-flex>
                            </template>
                          </n-dynamic-input>
                        </n-layout-content>
                      </n-layout>
                </NFormItem>
               </n-tab-pane>
            </n-tabs>
          </NForm>
        </CrudModal>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
